package MyTCP;

import java.io.DataOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
    public static void main(String[] args) throws IOException {
        //创建服务端管道对象
        ServerSocket serverSocket = new ServerSocket(8888);

        //等待接收客户端，创建管道对象
        Socket socket = serverSocket.accept();
        //创建完管道之后，就要创建字节流
        InputStream inputStream = socket.getInputStream();
        //再将低级流升级为高级流
        DataInputStream dis = new DataInputStream(inputStream);

        while (true) {
            try {
                //接着就可以读数据了
                String s = dis.readUTF();
                System.out.println(s);
                //通过管道对象来获取到发送消息的IP对象
                InetAddress clientInetAddress = socket.getInetAddress();
                //socket.getRemoteSocketAddress()
                //通过管道对象就可以获取到端口号
                int clientPort = socket.getPort();
                //通过IP对象就可以获取到IP地址
                String address = clientInetAddress.getHostAddress();
                //通过IP对象就可以获取到IP名字
                String clientName = clientInetAddress.getHostName();
                System.out.println("端口号: "+ clientPort + " ，IP名字: " + clientName + " ，IP地址: " + address);
                System.out.println("=====================");
            } catch (IOException e) {
                System.out.println(" IP名字: " + socket.getInetAddress().getHostName() + " ，IP地址: " + socket.getInetAddress().getHostAddress() + " 离线了!!!");
                dis.close();
                socket.close();
                break;
            }
        }
    }
}

